package core.service
{
import com.adobe.serialization.json.JSON;

import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLRequest;

/**h
 * DebugService
 * @author Jay
 * 
 */
public class DebugService extends EventDispatcher implements IService
{
	//==========================================================================
	//  Constructor
	//==========================================================================
    public function DebugService()
	{
		super();
	}
	//==========================================================================
	//  Properties
	//==========================================================================
	private var loadedCount:int = 0;
	
	private var queue:Vector.<Array> = new Vector.<Array>();   /* Array.<ServiceRequest> */
	//==========================================================================
	//  Public methods
	//==========================================================================
	public function invoke(request:ServiceRequest, ...args):void
	{
		queue.push([ request ].concat(args));
		
		if (queue.length == 1) process();
	}
	
	private function process():void
	{
		loadedCount = 0;
		
		var requests:Array = queue[0];
		
		for (var i:int = 0; i < requests.length; i++)
		{
			var loader:Invoker = new Invoker();
			loader.index = i;
			loader.addEventListener(Event.COMPLETE, dataLoadedHandler);
			loader.load(new URLRequest("../mock_data/" + ServiceRequest(requests[i]).method));
		}
	}
	
	private function dataLoadedHandler(event:Event):void
	{
		var loader:Invoker = event.target as Invoker;
		loader.removeEventListener(Event.COMPLETE, dataLoadedHandler);
		
		loadedCount ++;
		
		var requests:Array = queue[0];
		
		var request:ServiceRequest = requests[loader.index];
		
		var obj:*;
		
		try
		{
			obj = JSON.decode(loader.data);
		}
		catch (error:Error)
		{
			obj = String(loader.data);
		}
		
		request.response = new SuccessResponse(obj);
				
		if (loadedCount >= requests.length)
		{			
			for (var i:int = 0; i < requests.length; i++)
			{
				ServiceRequest(requests[i]).complete();
			}
			
			queue.shift();
			
			if (queue.length > 0) process();
		}
	}
}
}
import flash.net.URLLoader;

class Invoker extends URLLoader
{
	public var index:int = 0;
}




